<script setup lang="ts">
import { request } from '@/apis'
import DataItem from '@/components/DataItem.vue'
import {
  closeToast,
  showLoadingToast,
  showToast,
  type ActionSheetAction,
} from 'vant'
import { onMounted, ref, watch } from 'vue'
import base64ToBlob from 'b64-to-blob'
import { useCounterStore } from '@/stores/counter'
import { useRouter } from 'vue-router'

const store = useCounterStore()

const router = useRouter()

const profile = ref({} as ProfileInfo)

const gender = ref('')

watch(
  () => profile.value.gender,
  () => {
    if (profile.value.gender) {
      gender.value = '女'
    } else {
      gender.value = '男'
    }
  },
)

const exit = () => {
  jk.removeUser()
  profile.value = {} as ProfileInfo
  store.nickName = ''
  store.jianjie = ''
  jk.pop()
}

// 1. 修改头像
// 1.1 控制修改头像弹层的显示/隐藏
const showAvatarSheet = ref(false)
// 1.2 打开相册/相机
const onSelectAvatar = async (item: ActionSheetAction) => {
  // console.log('选择菜单时触发-onSelectAvatar', item, index)
  let dataStr = ''
  if (item.name === '相册') {
    dataStr = await jk.pickerPhoto()
    onUpdateAvatar(dataStr)
  } else if (item.name === '拍照') {
    dataStr = await jk.pickerCamera()
    onUpdateAvatar(dataStr)
  }
}
// 1.3 头像上传
const onUpdateAvatar = async (data: string) => {
  try {
    showAvatarSheet.value = false
    showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    // 把 base64 字符串转换
    const image = base64ToBlob(data, 'image/jpeg')
    // 后端要求传递 FormData 数据
    const fd = new FormData()
    // 按文档要求准备参数
    fd.append('photo', image, Date.now() + '.jpeg')
    const res = await request.patch<JkResponse<PhotoInfo>>(
      '/v1_0/user/photo',
      fd,
    )
    profile.value.photo = res.data.data.photo
    showToast({ message: '上传成功' })
  } catch {
    showToast({ message: '上传失败' })
  }
}

// 2. 选择生日
const showBirthdayPopup = ref(false)
// date-picker 组件的日期格式为数组 ['YYYY','MM','DD']
const birthday = ref(['', '', ''])
const onChangeBirthday = async (date: { selectedValues: string[] }) => {
  console.log(date)
  showBirthdayPopup.value = false
  // 把 selectedValues 转换成字符串，用于后端表单提交
  profile.value.birthday = date.selectedValues.join('-')
  console.log('修改生日', profile.value.birthday)
  await request.patch('/v1_0/user/profile', {
    birthday: profile.value.birthday,
  })
}

// 3. 选择性别
const showGenderSheet = ref(false)
const actions = [{ name: '男' }, { name: '女' }]
const onSelectGender = async (item: ActionSheetAction) => {
  if (item.name === '男') {
    await request.patch('/v1_0/user/profile', {
      gender: 0,
    })
  } else if (item.name === '女') {
    await request.patch('/v1_0/user/profile', {
      gender: 1,
    })
  }
  location.reload()
}
// 获取用户信息
onMounted(async () => {
  showLoadingToast({ message: '加载中...', duration: 0, forbidClick: true })
  const res = await request.get<JkResponse<ProfileInfo>>('/v1_0/user/profile')
  profile.value = res.data.data
  console.log('获取用户信息', res.data.data)
  birthday.value = profile.value.birthday.split('-')
  store.nickName = res.data.data.name
  store.jianjie = res.data.data.intro
  closeToast()
})
</script>

<template>
  <div class="container">
    <div class="top">
      <DataItem title="头像" @click="showAvatarSheet = true"
        ><img :src="profile.photo" alt=""
      /></DataItem>
      <DataItem title="昵称" @click="router.push('/nickname')">
        <p>{{ store.nickName }}</p></DataItem
      >
      <DataItem title="简介" @click="router.push('/jianjie')">
        <p>{{ store.jianjie }}</p>
      </DataItem>
    </div>
    <div class="body">
      <DataItem title="性别" @click="showGenderSheet = true">
        <p>{{ gender }}</p>
      </DataItem>
      <DataItem title="生日">
        <p @click="showBirthdayPopup = true">{{ profile.birthday }}</p>
      </DataItem>
      <p class="exit" @click="exit">退出登录</p>
    </div>
    <div>
      <van-action-sheet
        v-model:show="showAvatarSheet"
        :actions="[{ name: '相册' }, { name: '拍照' }]"
        @select="onSelectAvatar"
        cancel-text="取消"
        :style="{ paddingBottom: '20px' }"
      ></van-action-sheet>
      <!-- 选择生日弹层 -->
      <van-popup v-model:show="showBirthdayPopup" round position="bottom">
        <van-date-picker
          title="选择日期"
          @cancel="showBirthdayPopup = false"
          @confirm="onChangeBirthday"
          :min-date="new Date('1980-01-01')"
          :max-date="new Date()"
          v-model="birthday"
        />
      </van-popup>
      <!-- 选择性别 -->
      <van-action-sheet
        v-model:show="showGenderSheet"
        :actions="actions"
        @select="onSelectGender"
        :style="{ paddingBottom: '20px' }"
      />
    </div>
  </div>
</template>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  width: 100vw;
  height: 100vh;
}
input {
  width: auto !important ;
  border: none;
  outline: none;
  box-sizing: border-box;
  min-width: 20px;
}
img {
  width: 20px;
  height: 20px;
  border-radius: 10px;
}
p {
  color: #969899;
}
.row {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
.space {
  margin-right: 10px;
}
.top {
  width: 100%;
  background-color: white;
}
.body {
  width: 100%;
  background-color: white;
  margin-top: 20px;
  flex-grow: 1;
}
.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}
.exit {
  margin-top: 55vh;
  text-align: center;
  color: #fc6627;
}
</style>
